package com.rzjm.api.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.netty.water.SendUtil;
import com.rzjm.api.netty.water.entity.SendData;
import com.rzjm.api.netty.water.entity.SendObjectData;
import com.rzjm.api.service.*;
import com.rzjm.api.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.rzjm.api.constant.CommonConstants.SUCCESS;
import static com.rzjm.api.netty.water.constant.SendRtEnum.*;

/**
 *@Author: ZhouWei
 *@Description:  水机的主动控制类
 *@Date 2018-05-10
 */
@Slf4j
@Component
@RestController
@RequestMapping("/device/water")//url:模块/资源/{}/细分
public class DeviceWaterController extends BaseController {

    @Resource
    private ChargerOrderService chargerOrderService;
    @Resource
    private ChargerPortRecordService portRecordService;
    @Resource
    private IDeviceWaterService deviceWaterService;
    @Resource
    private IDeviceWaterUpdateVersionService deviceWaterUpdateVersionService;
    @Resource
    private IDeviceWaterOrderService deviceWaterOrderService;
    @Resource
    private IWaterIdCardService waterIdCardService;

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    @Value("${web.uploadPath}")
    private String uploadPath;

    /**
     *  重新获取配置信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/test")
    public JSONObject test(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int charger_id = jsonRequest.containsKey("charger_id") ? jsonRequest.getInt("charger_id") : 0;
            String order_no = jsonRequest.containsKey("order_no") ? jsonRequest.getStr("order_no") : "";

            ChargerOrder chargerOrder = chargerOrderService.getOrderByOrderNo(order_no);
            double bb = portRecordService.getChargerCapacity(chargerOrder);


            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",bb),true,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  支付成功后的出水命令
     * @param
     * @throws Exception
     */
    @PostMapping(value="/start/effluent")
    public JSONObject effluent(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("设备重置请求参数 : " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;

            DeviceWater deviceWater = deviceWaterService.findById(device_id);
            if(deviceWater == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备不存在"),true,true);
            }

            DeviceWaterOrder waterOrder = deviceWaterOrderService.findById(order_id);
            if(waterOrder == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单不存在"),true,true);
            }

            /**
             * 订单状态 0 - 未支付   1 - 支付中  2 - 已支付  3 - 充电中  4 - 已发起退款  5 - 退款完成  6 - 退款失败  7 - 订单已完成（结束） 8 -  订单取消
             */
            if(waterOrder.getStatus() < 2){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单未支付"),true,true);
            } else if(waterOrder.getStatus() == 8){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单已取消"),true,true);
            } else if(waterOrder.getStatus() == 2){
                SendObjectData sendData = new SendObjectData();
                sendData.setRt(SEND_RT_4.getRt());
                sendData.setV1(waterOrder.getOrderNo());//订单号
                sendData.setV2((int)(deviceWater.getSingleVolume().doubleValue() * 1000));//单次出水量
                int singlePrice = (int)(deviceWater.getSinglePrice().doubleValue() * 100);
                sendData.setV3(singlePrice);//单次价格
                String timespan = String.valueOf(new Date().getTime());

                sendData.setV4(timespan);//时间戳
                String crcV2 = "04";
                String crcTimespan = ByteUtil.int2Hex(Integer.parseInt(timespan.substring(timespan.length() - 2, timespan.length())));
                if(crcTimespan.length() % 2 == 1){
                    crcTimespan = "0" + crcTimespan;
                }

                String moneyStr = singlePrice+"";
                String crcMoney = ByteUtil.int2Hex(Integer.parseInt(moneyStr.substring(moneyStr.length() - 2, moneyStr.length())));
                if(crcMoney.length() % 2 == 1){
                    crcMoney = "0" + crcMoney;
                }

                //crc 校验
                System.out.println("crcV2 = " + crcV2);
                System.out.println("crcMoney = " + crcMoney);
                System.out.println("crcTimespan = " + crcTimespan);

                String crc = getSignCrc(crcV2, crcMoney, crcTimespan);
                System.out.println("crc = " + crc);
                sendData.setV5(crc);//crc校验
                sendData.setV6(ByteUtil.getIntByHex(crc));//crc校验  10进制

                // devicesList 批量设备控制，不用等回
                R<Object> result =  SendUtil.sentCommand(deviceWater, sendData, true);
                if (result.getCode() == SUCCESS) {
                    System.out.println("操作成功" + result.toString());
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"操作成功"),true,true);
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"操作失败"),true,true);
                }
            }else{
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"订单状态无效"),true,true);
            }


        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     * 获取签名 crc校验
     * @param v2
     * @param money
     * @param timespan
     * @return
     */
    private String getSignCrc(String v2, String money, String timespan){
        //低位在前，CRC校验3个字节，RT+剩余金额后两位+时间戳后两位
//        例：RT：02
//        金额：91=0x5B
//        时间戳64=0x40
//        结果：EAC0
        String crcData = v2 + money + timespan;
        System.out.println("校验串：" + crcData);
        String crc = CRCUtil.getCrc(crcData);
        return crc;
    }

    /**
     *  版本更新
     * @param
     * @throws Exception
     */
    @PostMapping(value="/update/version")
    public JSONObject updateVersion(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("版本更新修改: " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            int version_id = jsonRequest.containsKey("version_id") ? jsonRequest.getInt("version_id") : 0;

            DeviceWater deviceWater = deviceWaterService.findById(device_id);
            if(deviceWater == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备不存在"),true,true);
            }

            DeviceWaterUpdateVersion updateVersion = deviceWaterUpdateVersionService.findById(version_id);
            if(updateVersion == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该版本不存在"),true,true);
            }

            String filePath = uploadPath + File.separator +updateVersion.getFileUrl();
            ByteBuffer out = ByteBuffer.allocate(256);
            SendObjectData sendData = new SendObjectData();
            byte[] fileData;
            try {
                fileData = ByteUtil.fileToByteArray(filePath);
                int packageTotal = fileData.length / 1024 + ((fileData.length % 1024) == 0 ? 0 : 1);
                System.out.println("总分包数：" + packageTotal);
//                sendData.setRt(SEND_RT_44.getRt());
//                sendData.setV1(updateVersion.getUpdateVersion());
//                sendData.setV2(packageTotal);
//                // devicesList 批量设备控制，不用等回
//                R<Object> result =  SendUtil.sentCommand(deviceWater, sendData, false);
                //报文头
                out.put((byte) 0x7F);
                out.put((byte) 0xC0);
                out.put((byte) 0x00);
                out.put((byte) 0x01);
                //数据长度
                out.put((byte) 0x00);
                out.put((byte) 0x17);
                //固件包信息
                out.put((byte) 0x01);
                //总包字节数
                out.putInt(fileData.length);
                //分包数量
                out.putShort((short) packageTotal);
                //总包CRC
                byte[] crc = CRCUtil.getCrcByte(fileData);
                out.put(crc);
                //版本号
//            byte[] version = ByteUtil.stringToAscii("v2.0.2-A", 10);
                byte[] version = ByteUtil.stringToAscii(updateVersion.getUpdateVersion(), 10);
                out.put(version);
                //校验
                out.flip();
                byte[] enBytes = new byte[out.limit()];
                //截取有效报文
                out.get(enBytes);
//            String crc1 = CRCUtil.getCRC(enBytes);
                String crc1 = CRCUtil.calculateCRC16Str(enBytes);
                //完整报文
                String dataStr = ByteUtil.hex2String(enBytes)+crc1;
                log.info("type44===>{}",dataStr);
                //发送
                SendUtil.reply(ByteUtil.hexStringToByteArray(dataStr), deviceWater.getId());
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"操作成功"),true,true);
            } catch (IOException e) {
                System.out.println("获取升级文件失败：" + e.getMessage());
                // devicesList 批量设备控制，不用等回
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"获取升级文件失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  设备重置
     * @param
     * @throws Exception
     */
    @PostMapping(value="/resetDevice")
    public JSONObject resetDevice(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("设备重置请求参数 : " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            int op_type = jsonRequest.containsKey("op_type") ? jsonRequest.getInt("op_type") : 0;

            DeviceWater deviceWater = deviceWaterService.findById(device_id);
            if(deviceWater == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备不存在"),true,true);
            }

            SendData sendData = new SendData();
            sendData.setRt(SEND_RT_10.getRt());
            sendData.setV1(op_type);
            // devicesList 批量设备控制，不用等回
            R<Object> result =  SendUtil.sentCommand(deviceWater, sendData, false);
//            if (result.getCode() == SUCCESS) {
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"操作成功"),true,true);
//            }else{
//                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"操作失败"),true,true);
//            }
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  臭氧控制
     * @param
     * @throws Exception
     */
    @PostMapping(value="/control/ozone")
    public JSONObject controlOzone(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("臭氧控制: " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;// 0：关闭 1：开启

            DeviceWater deviceWater = deviceWaterService.findById(device_id);
            if(deviceWater == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备不存在"),true,true);
            }

            SendData sendData = new SendData();
            sendData.setRt(SEND_RT_11.getRt());
            sendData.setV1(state);
            // devicesList 批量设备控制，不用等回
            R<Object> result =  SendUtil.sentCommand(deviceWater, sendData, false);
//            if (result.getCode() == SUCCESS) {
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"操作成功"),true,true);
//            }else{
//                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"操作失败"),true,true);
//            }
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  温控的控制
     * @param
     * @throws Exception
     */
    @PostMapping(value="/control/temperature")
    public JSONObject controlTemperature(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("温控的控制: " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            int op_type = jsonRequest.containsKey("op_type") ? jsonRequest.getInt("op_type") : 0;


            DeviceWater deviceWater = deviceWaterService.findById(device_id);
            if(deviceWater == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备不存在"),true,true);
            }

            SendData sendData = new SendData();
            sendData.setRt(SEND_RT_6.getRt());
            sendData.setV1(op_type);
            // devicesList 批量设备控制，不用等回
            R<Object> result =  SendUtil.sentCommand(deviceWater, sendData, false);
//            if (result.getCode() == SUCCESS) {
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"操作成功"),true,true);
//            }else{
//                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"操作失败"),true,true);
//            }
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  广告灯的控制
     * @param
     * @throws Exception
     */
    @PostMapping(value="/ad/light")
    public JSONObject adLightControl(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("广告灯的控制: " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            int op_type = jsonRequest.containsKey("op_type") ? jsonRequest.getInt("op_type") : 0;


            DeviceWater deviceWater = deviceWaterService.findById(device_id);
            if(deviceWater == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备不存在"),true,true);
            }

            SendData sendData = new SendData();
            sendData.setRt(SEND_RT_5.getRt());
            sendData.setV1(op_type);
            // devicesList 批量设备控制，不用等回
            R<Object> result =  SendUtil.sentCommand(deviceWater, sendData, false);
//            if (result.getCode() == SUCCESS) {
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"操作成功"),true,true);
//            }else{
//                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"操作失败"),true,true);
//            }
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  脉冲数变动
     * @param
     * @throws Exception
     */
    @PostMapping(value="/pulse/change")
    public JSONObject pulseChange(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("脉冲数变动修改: " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            int low_pulse = jsonRequest.containsKey("low_pulse") ? jsonRequest.getInt("low_pulse") : 0;
            int middle_pulse = jsonRequest.containsKey("middle_pulse") ? jsonRequest.getInt("middle_pulse") : 0;
            int high_pulse = jsonRequest.containsKey("high_pulse") ? jsonRequest.getInt("high_pulse") : 0;


            DeviceWater deviceWater = deviceWaterService.findById(device_id);
            if(deviceWater == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备不存在"),true,true);
            }

            SendData sendData = new SendData();
            sendData.setRt(SEND_RT_12.getRt());
            sendData.setV1(low_pulse);
            sendData.setV2(middle_pulse);
            sendData.setV3(high_pulse);
            // devicesList 批量设备控制，不用等回
            R<Object> result =  SendUtil.sentCommand(deviceWater, sendData, false);
//            if (result.getCode() == SUCCESS) {
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"操作成功"),true,true);
//            }else{
//                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"操作失败"),true,true);
//            }
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  清楚故障码
     * @param
     * @throws Exception
     */
    @PostMapping(value="/clean/error")
    public JSONObject cleanError(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("清除故障码: " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;

            DeviceWater deviceWater = deviceWaterService.findById(device_id);
            if(deviceWater == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备不存在"),true,true);
            }

            SendData sendData = new SendData();
            sendData.setRt(SEND_RT_7.getRt());
            // devicesList 批量设备控制，不用等回
            R<Object> result = SendUtil.sentCommand(deviceWater, sendData, true);
//            if (result.getCode() == SUCCESS) {
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"操作成功"),true,true);
//            }else{
//                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"操作失败"),true,true);
//            }
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  清洗水罐参数设置
     * @param
     * @throws Exception
     */
    @PostMapping(value="/clean/tanks")
    public JSONObject cleanOp(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("清洗水罐参数设置: " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int device_id = jsonRequest.containsKey("device_id") ? jsonRequest.getInt("device_id") : 0;
            int clean_second = jsonRequest.containsKey("clean_second") ? jsonRequest.getInt("clean_second") : 0;
            int tank_height = jsonRequest.containsKey("tank_height") ? jsonRequest.getInt("tank_height") : 0;

            DeviceWater deviceWater = deviceWaterService.findById(device_id);
            if(deviceWater == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"设备不存在"),true,true);
            }

            SendData sendData = new SendData();
            sendData.setRt(SEND_RT_8.getRt());
            sendData.setV1(clean_second);
            sendData.setV2(tank_height);
            // devicesList 批量设备控制，不用等回
            R<Object> result = SendUtil.sentCommand(deviceWater, sendData, true);
//            if (result.getCode() == SUCCESS) {
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"操作成功"),true,true);
//            }else{
//                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"操作失败"),true,true);
//            }
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }



    /**
     *  获取水卡卡面编号获取水卡信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getCardInfoByNum")
    public JSONObject getCardInfoByNum(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("设备重置请求参数 : " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            String cardNum = jsonRequest.containsKey("cardNum") ? jsonRequest.getStr("cardNum") : "";

            QueryWrapper<WaterIdCard> qw = new QueryWrapper<>();
            qw.eq("card_num", cardNum);
            qw.last("limit 1");
            WaterIdCard card = waterIdCardService.getOne(qw);
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功", card),true,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  获取最后一个水卡编号信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getLastCardIdInfo")
    public JSONObject getLastCardIdInfo(){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            QueryWrapper<WaterIdCard> qw = new QueryWrapper<>();
            qw.orderByDesc("card_num");
            qw.last("limit 1");
            WaterIdCard card = waterIdCardService.getOne(qw);
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功", card),true,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  获取水卡编号信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getCardIdInfo")
    public JSONObject getCardIdInfo(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("获取水卡编号信息 : " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            String cardId = jsonRequest.containsKey("cardId") ? jsonRequest.getStr("cardId") : "";

            QueryWrapper<WaterIdCard> qw = new QueryWrapper<>();
            qw.eq("ic_card_id", cardId);
            qw.last("limit 1");
            WaterIdCard card = waterIdCardService.getOne(qw);
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功", card),true,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  水卡编号上传卡库
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addCardId")
    public JSONObject addCardId(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("设备重置请求参数 : " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String cardId = jsonRequest.containsKey("cardId") ? jsonRequest.getStr("cardId") : "";
            String cardNum = jsonRequest.containsKey("cardNum") ? jsonRequest.getStr("cardNum") : "";
            String keyA = jsonRequest.containsKey("keyA") ? jsonRequest.getStr("keyA") : "";

            QueryWrapper<WaterIdCard> qw = new QueryWrapper<>();
            qw.eq("ic_card_id", cardId);
            qw.last("limit 1");
            WaterIdCard card = waterIdCardService.getOne(qw);
            if(card == null){
                card = new WaterIdCard();
                card.setCardNum(cardNum);
                card.setIcCardId(cardId);
                card.setKeyA(keyA);
                card.setCreateTime(new Date());
                boolean bl = waterIdCardService.save(card);
                if(bl){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"添加成功"),true,true);
                }
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"添加失败"),true,true);
            }else{
                card.setCardNum(cardNum);
                card.setIcCardId(cardId);
                card.setKeyA(keyA);
                boolean bl = waterIdCardService.updateById(card);
                if(bl){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"修改成功"),true,true);
                }
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"修改失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

}
